package cqrtplm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.common.model.dto.search.SearchConditionDTO;
import com.hustcad.plm.pdm.common.model.vo.tableview.TableViewDescriptorVO;
import com.hustcad.plm.pdm.common.service.tableview.TyplmCommonTableViewService;
import com.hustcad.plm.pdm.folder.model.dto.HyperlinkDTO;
import com.hustcad.plm.pdm.folder.model.dto.filter.TySubFolderFilterDTO;
import com.hustcad.plm.pdm.folder.model.dto.filter.TySubFolderFilterQuery;
import com.hustcad.plm.pdm.folder.model.dto.filter.TyplmFolderObjDTO;
import com.hustcad.plm.pdm.folder.model.dto.move.BatchMoveOidParamDTO;
import com.hustcad.plm.pdm.folder.model.dto.move.MoveOidParamDTO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderVO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderWebVO;
import com.hustcad.plm.pdm.folder.service.TyplmCommonMoveService;
import com.hustcad.plm.pdm.folder.service.TyplmHyperlinkService;
import com.hustcad.plm.pdm.folder.service.TyplmSubFolderLinkService;
import com.hustcad.plm.pdm.folder.service.search.TyplmSubFilterObjectService;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import cqrtplm.entity.ObjectStorageDO;
import cqrtplm.mapper.StoragePlanningMapper;
import cqrtplm.service.DocFolderOperationService;
import cqrtplm.service.ObjectStorageService;
import cqrtplm.service.RTCDecryptionService;
import cqrtplm.vo.PDFProjectVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class RTCDecryptionServiceImpl implements RTCDecryptionService {

    @Resource
    private TyplmCommonMoveService typlmCommonMoveService;

    @Resource
    private TyplmHyperlinkService typlmHyperlinkService;

    @Resource
    private StoragePlanningMapper storagePlanningMapper;

    @Resource
    private TyplmSubFolderLinkService typlmSubFolderLinkService;

    @Resource
    private TyplmSubFilterObjectService typlmSubFilterObjectService;

    @Resource
    private TyplmCommonTableViewService typlmCommonTableViewService;

    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private ObjectStorageService objectStorageService;




    @Override
    public void decryption(String containerId, String type) {

        if (type.equals("解密")){
            String cabinetId = storagePlanningMapper.selectCabinetIdByOid2(containerId);
            List<SubfolderWebVO> subfolderWebVOS = typlmSubFolderLinkService.querySubFolderListByParent(
                    new BigInteger(cabinetId), "ty.inteplm.folder.CTyCabinet");
            Iterator<SubfolderWebVO> iterator = subfolderWebVOS.iterator();
            List<TyplmFolderObjDTO> list=new ArrayList<>();

            TableViewDescriptorVO tableViewDescriptorDetail = typlmCommonTableViewService.getTableViewDescriptorDetail(
                    new IdentifierEntity(new BigInteger("363292770112602112"), "ty.inteplm.folder.CTyTableViewDescriptor"));
            //遍历文件夹
            while (iterator.hasNext()){
                SubfolderWebVO subfolderWebVO = iterator.next();
                Callback(list,subfolderWebVO,tableViewDescriptorDetail);
            }
            Iterator<TyplmFolderObjDTO> typlmFolderObjDTOIterator = list.iterator();


            BatchMoveOidParamDTO batchMoveOidParamDTO=new BatchMoveOidParamDTO();
            batchMoveOidParamDTO.setUpdateAllVersion(true);
            List<MoveOidParamDTO> moveList=new ArrayList<>();
            List<HyperlinkDTO> hyperlinkList=new ArrayList<>();

            while (typlmFolderObjDTOIterator.hasNext()){
                TyplmFolderObjDTO typlmFolderObjDTO = typlmFolderObjDTOIterator.next();

                ObjectStorageDO objectStorageDO = objectStorageService.selectOneByTypeDefName(
                        typlmFolderObjDTO.getTypeDefName());
                //判断枚举中是否存在对应关系
                if(ObjectUtil.isNotEmpty(objectStorageDO)){
                    PDFProjectVO pdfProjectVO = storagePlanningMapper.selectPdmIds(objectStorageDO.getContextName());
                    //判断产品库是否存在
                    if (ObjectUtil.isNotEmpty(pdfProjectVO)){
                        String folderId = null;

                        String[] split = objectStorageDO.getFolderPath().split("/");
                        for (int i = 0; i < split.length; i++) {
                            String id=null;
                            if (StrUtil.isBlank(split[i])) {
                                continue;
                            }
                            if (i==1){
                                id= storagePlanningMapper.selectOidByNameAndCid(pdfProjectVO.getOId(),
                                                                                split[i], "0");
                                if (StrUtil.isNotBlank(id)) {
                                    folderId=id;
                                }
                            }else {
                                id = storagePlanningMapper.selectOidByNameAndCid(pdfProjectVO.getOId(), split[i], folderId);
                                if (StrUtil.isNotBlank(id)) {
                                    folderId= storagePlanningMapper.selectOidByNameAndCid(pdfProjectVO.getOId(),
                                                                                          split[i], folderId);
                                }

                            }
                            if (StrUtil.isBlank(id)){
                                //创建文件夹
                                SubfolderVO subfolder=new SubfolderVO();
                                subfolder.setName(split[i]);
                                subfolder.setDescription("--系统自动创建--文件夹--");
                                subfolder.setParentOid(i==1?pdfProjectVO.getDefaultcabinetoid():folderId);
                                subfolder.setParentOtype(i==1?"ty.inteplm.folder.CTyCabinet":"ty.inteplm.folder.CTySubFolder");
                                SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                                folderId=subfolderWebVO.getOid();
                            }
                        }




                        IdentifierEntity entityIdentifier = new IdentifierEntity(typlmFolderObjDTO.getOid(),typlmFolderObjDTO.getOtype());
                        IdentifierEntity folderIdentifier = new IdentifierEntity(new BigInteger(folderId),"ty.inteplm.folder.CTySubFolder");
                        moveList.add(new MoveOidParamDTO(entityIdentifier,folderIdentifier));

                        HyperlinkDTO hyperlinkDTO=new HyperlinkDTO();
                        hyperlinkDTO.setOid(typlmFolderObjDTO.getOid());
                        hyperlinkDTO.setBranchid(typlmFolderObjDTO.getBranchid());
                        hyperlinkDTO.setOtype(typlmFolderObjDTO.getOtype());
                        hyperlinkDTO.setCabinetoid(new BigInteger(cabinetId));
                        hyperlinkDTO.setCabinetotype("ty.inteplm.folder.CTyCabinet");
                        hyperlinkDTO.setContaineroid(new BigInteger(containerId));
                        hyperlinkDTO.setContainerotype("ty.inteplm.project.CTyProject");
                        //                    hyperlinkDTO.setContainerName();
                        hyperlinkDTO.setName(typlmFolderObjDTO.getNumber()+","+typlmFolderObjDTO.getName());
                        hyperlinkDTO.setSubfolderoid(typlmFolderObjDTO.getSubfolderoid());
                        hyperlinkDTO.setSubfolderotype("ty.inteplm.folder.CTySubFolder");
                        hyperlinkDTO.setPath("/"+typlmFolderObjDTO.getContextName()+"/");
                        hyperlinkList.add(hyperlinkDTO);
                    }
                }

            }
            batchMoveOidParamDTO.setMoveList(moveList);

            DocFolderOperationService docFolderOperationService = SpringUtil.getBean(DocFolderOperationService.class);
            //修改项目为非密
            String attributesID = storagePlanningMapper.queryExtendedAttributesID(
                    containerId, "密级");


            //项目解密
            ModifyTheValueOfTheExtendedAttribute(containerId,attributesID);
            //交付物解密
            deliverableDecryption(list);
            //创建文件超链接
            typlmHyperlinkService.batchCreateHyperlink(hyperlinkList);
            //移动原文件
            typlmCommonMoveService.moveObjects(batchMoveOidParamDTO);
        }else if (type.equals("加密")){
            String attributesID = storagePlanningMapper.queryExtendedAttributesID(
                    containerId, "密级");
            String result = storagePlanningMapper.selectValExist(containerId,
                                                                 attributesID);
            if (StrUtil.isNotBlank(result) && NumberUtil.isInteger(result) && Integer.parseInt(result) > 0){
                storagePlanningMapper.ModifyTheValueOfTheExtendedAttribute(containerId, attributesID, "加密");
            }else {
                String oid = snowflakeIdComponent.getInstance().nextId().toString();
                storagePlanningMapper.insertAttVal(attributesID, containerId, oid, "加密");
            }
        }else {
            throw new RuntimeException("错误的的type类型");
        }
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void deliverableDecryption(List<TyplmFolderObjDTO> list){
        for (TyplmFolderObjDTO typlmFolderObjDTO:list){
            if(typlmFolderObjDTO.getOtype().equals("ty.inteplm.doc.CTyDoc")){
                storagePlanningMapper.updateDocSecuritylabels(typlmFolderObjDTO.getOid().toString());
            } else if (typlmFolderObjDTO.getOtype().equals("ty.inteplm.part.CTyPart")) {
                storagePlanningMapper.updatePartSecuritylabels(typlmFolderObjDTO.getOid().toString());
            } else if(typlmFolderObjDTO.getOtype().equals("ty.inteplm.cad.CTyCADDoc")){
                storagePlanningMapper.updateCadDocSecuritylabels(typlmFolderObjDTO.getOid().toString());
            }
        }
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void ModifyTheValueOfTheExtendedAttribute(String containerId,String attributesID) {
        String result = storagePlanningMapper.selectValExist(containerId,
                                                             attributesID);
        if (StrUtil.isNotBlank(result) && NumberUtil.isInteger(result) && Integer.parseInt(result) > 0){
            storagePlanningMapper.ModifyTheValueOfTheExtendedAttribute(containerId, attributesID, "非密");
        }else {
            String oid = snowflakeIdComponent.getInstance().nextId().toString();
            storagePlanningMapper.insertAttVal(attributesID, containerId, oid, "非密");
        }
    }
    public void Callback(List<TyplmFolderObjDTO> list,SubfolderWebVO subfolderWebVO,TableViewDescriptorVO tableViewDescriptorDetail){

        List<SubfolderWebVO> subfolderWebVOS = typlmSubFolderLinkService.querySubFolderListByParent(
                new BigInteger(subfolderWebVO.getOid()), "ty.inteplm.folder.CTySubFolder");

        TySubFolderFilterQuery tySubFolderFilterQuery = new TySubFolderFilterQuery();
        tySubFolderFilterQuery.setSubFolderOid(new BigInteger(subfolderWebVO.getOid()));
        tySubFolderFilterQuery.setSubFolderOtype("ty.inteplm.folder.CTySubFolder");
        tySubFolderFilterQuery.setNeedCount(true);
        tySubFolderFilterQuery.setCurPage(1);
        tySubFolderFilterQuery.setPageSize(999);
        TySubFolderFilterDTO tySubFolderFilterDTO = new TySubFolderFilterDTO();
        tySubFolderFilterDTO.setName("全部");
        tySubFolderFilterDTO.setPublished(1l);
        tySubFolderFilterDTO.setHidden(0l);
        tySubFolderFilterDTO.setKeyWords("");
        tySubFolderFilterDTO.setOtype("ty.inteplm.folder.CTyTableViewDescriptor");
        tySubFolderFilterDTO.setSearchColumnList(tySubFolderFilterDTO.getSearchColumnList());
        tySubFolderFilterDTO.setOid(new BigInteger("363292770112602112"));
        tySubFolderFilterDTO.setSearchCondition(
                BeanUtil.copyProperties(tableViewDescriptorDetail.getSearchCondition(), SearchConditionDTO.class, "showAllViewVersion", "tableId", "excludeTypeInthidList", "showAllViewVersion"));
        tySubFolderFilterQuery.setSubFolderFilterDTO(tySubFolderFilterDTO);

        List<TyplmFolderObjDTO> dtos = typlmSubFilterObjectService.getFolderObjectByFilter(tySubFolderFilterQuery)
                .getList();

        if (CollUtil.isNotEmpty(dtos)){
            list.addAll(dtos);
        }

        if (CollUtil.isEmpty(subfolderWebVOS)){
            return;
        }

        Iterator<SubfolderWebVO> iterator = subfolderWebVOS.iterator();
        while (iterator.hasNext()){
            SubfolderWebVO vo = iterator.next();
            Callback(list,vo,tableViewDescriptorDetail);
        }

    }

}
